import Axios from 'axios';
import Message from 'iview/src/components/message';

/**
 * 设置公共请求头access_token
*/
// const access_token = utils.getCookie('access_token');
// Axios.defaults.headers.common['Authorization'] = `bearer ${access_token}`;

/**
 * post
 * @param  {String} url    [地址]
 * @param  {Object} params [参数]
 * @return {Object}        [Promise]
 */
export const $get = (url, params) => {
	return new Promise((resolve, reject) => {
		Axios.get(url, {
			params: {
				...params,
				_t: new Date().getTime(),
			}
		}).then((res) => {
			if (res.statusText == 'OK') {
                if (res.data.code == 0) {
                    resolve(res.data)
                } else {
					failMessage(res.data.message);
                }
			} else {
				failMessage('获取数据失败');
				reject(res)
			}
		}).catch((mes) => {
			failMessage('获取数据失败');
			reject(mes)
		})
	})
}
/**
 * post
 * @param  {String} url    [地址]
 * @param  {Object} params [参数]
 * @param  {String} type   [可不传，设定为form为formdata提交]
 * @return {Object}        [Promise]
 */
export const $post = (url, params, type) => {
	if (type == 'form') {
		return new Promise((resolve, reject) => {
			Axios.post(url, params).then((res) => {
				if (res.statusText == 'OK') {
                    if (res.data.code == 0) {
                        resolve(res.data)
                    } else {
                        failMessage(res.data.message);
                    }
				} else {
					failMessage()
					reject(res)
				}
			}).catch((mes) => {
				failMessage()
				reject(mes)
			})
		})
	} else {
		return new Promise((resolve, reject) => {
			Axios.post(url, {
				...params
			}).then((res) => {
				if (res.statusText == 'OK') {
                    if (res.data.code == 0) {
                        resolve(res.data)
                    } else {
                        failMessage(res.data.message);
                    }
				} else {
					failMessage('获取数据失败');
					reject(res)
				}
			}).catch((mes) => {
				failMessage('获取数据失败');
				reject(mes);
			})
		})
	}
}


function failMessage(msg) {
	Message.warning({
		content: msg,
		duration: 2,
		closable: true
	});
}
